<?php

namespace App\Admin\Controllers;

use App\Models\Permission;
use App\Models\Role;
use App\Models\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;


class UserController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $content->breadcrumb(
            ['text' => '首页', 'url' => '/'],
            ['text' => '用户管理', 'url' => '/users']
        );

        return $content
            ->header('用户管理')
            ->description('管理博客用户')
            ->body($this->grid());
    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('用户详情')
            ->description('前台用户详情')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        $content->breadcrumb(
            ['text' => '首页', 'url' => '/'],
            ['text' => '用户管理', 'url' => '/users'],
            ['text' => '编辑用户']
        );
        return $content
            ->header('用户编辑')
            ->description('')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('新建用户')
            ->description('新建前台用户')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new User);
        //筛选框控制
        $grid->filter(function ($filter){
            //1.时间段筛选   设置created_at字段的范围查询
            $filter->between('created_at', '创建时间')->datetime();
            //1.时间段筛选   设置created_at字段的范围查询
            $filter->between('updated_at', '修改时间')->datetime();
            //2.字段模糊查询 like = '% %'
            $filter->like('name', '姓名');
            //3.字段equal 筛选
            $filter->like('email', '邮箱');
//            $filter->equal('email', '邮箱');
            //4.去掉默认的ID搜索
            $filter->disableIdFilter();
            //5.性别筛选
            $filter->equal('sex','性别')->select(['男'=>'男','女'=>'女']);

        });
        $grid->id('ID')->sortable();
        $grid->roles('角色')->pluck('name')->label();
        $grid->name('昵称')->display(function($text) {
            return str_limit($text, 15, '...');
        });;
        $grid->sex('性别');
        $grid->avatar('头像')->display(function ($avatar) {
            if (substr($avatar , 0 , 4)=='http')
                return "<img src='$avatar' width='30' height='30'/>";
            else
                return "<img src='upload/$avatar' width='30' height='30'/>";
        });
        $grid->email('邮箱');
        $grid->email_verified_at('邮箱验证时间');
        $grid->introduction('个人简介')->display(function($text) {
            return str_limit($text, 20, '...');
        });
        $grid->created_at('创建时间');
        $grid->updated_at('更新时间');
        $grid->paginate(15);
        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(User::findOrFail($id));

        $show->name('昵称');
        $show->avatar('头像')->image();
        $show->email('邮箱');
        $show->email_verified_at('邮箱验证时间');
        $show->introduction('个人简介');
        $show->created_at('创建时间');
        $show->updated_at('更新时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new User());
        $roleModel =new  Role();
        $permissionModel = new Permission();
        $id = request()->route('user');
        //非重验证
        if ($id){
            $form->text('name', '昵称')->rules("required|unique:users,name,{$id},id");
            $form->email('email', '邮箱')->rules("required|unique:users,email,{$id},id");
        }else{
            $form->text('name', '昵称')->rules("required|unique:users");
            $form->email('email', '邮箱')->rules('required|unique:users');
        }
        $form->multipleSelect('roles', '角色')->options($roleModel::all()->pluck('name', 'id'));
        $form->multipleSelect('permissions', '权限')->options($permissionModel::all()->pluck('name', 'id'));
        $form->image('avatar', '头像')->uniqueName()->move('avatar');
        $form->text('introduction', '个人简介');
        $form->password('password', '密码')->rules('confirmed|required')
            ->default(function ($form) {
                return $form->model()->password;
            });;
        $form->password('password_confirmation','确认密码')->rules('required')
            ->default(function ($form) {
                return $form->model()->password;
            });
        $form->datetime('email_verified_at', '邮箱验证时间')->default(date('Y-m-d H:i:s'));
//        $form->setAction(admin_base_path('users'));

        $form->ignore(['password_confirmation']);

        $form->footer(function ($footer) {
            // 去掉`重置`按钮
            $footer->disableReset();
            // 去掉`查看`checkbox
            $footer->disableViewCheck();
            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();
            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();

        });
        $form->saving(function (Form $form) {
            $form->updated_at = date('Y-m-d H:i:s',time());
            if ($form->password && $form->model()->password != $form->password) {
                $form->password = bcrypt($form->password);
            }
        });

        $form->saved(function (Form $form) {
            $form->model()->save();
            admin_toastr('用户修改成功');

            return redirect(admin_base_path('users'));
        });
        return $form;
    }
}
